package backend

import (
	"fmt"
	"log"
	"time"
)

// WitsService WITS数据服务，集成DAO工具类
type WitsService struct {
	dbClient *WitsDbClient
}

// NewWitsService 创建WITS数据服务
func NewWitsService(dataDir string) (*WitsService, error) {
	dbClient, err := NewWitsDbClient(dataDir)
	if err != nil {
		return nil, fmt.Errorf("failed to create WITS database client: %v", err)
	}

	return &WitsService{
		dbClient: dbClient,
	}, nil
}

// Close 关闭服务
func (s *WitsService) Close() error {
	return s.dbClient.Close()
}

// SaveWitsData 保存WITS数据
func (s *WitsService) SaveWitsData(data *WitsData) error {
	if err := s.dbClient.InsertWitsData(data); err != nil {
		log.Printf("Failed to save WITS data: %v", err)
		return err
	}
	return nil
}

// GetHistoricalData 获取历史数据（按时间范围）
func (s *WitsService) GetHistoricalData(startTime, endTime int64) ([]*WitsData, error) {
	start := time.Unix(startTime, 0)
	end := time.Unix(endTime, 0)

	return s.dbClient.QueryByTimeRange(start, end)
}

// GetWellData 获取指定井的历史数据
func (s *WitsService) GetWellData(wellID string, startTime, endTime int64) ([]*WitsData, error) {
	start := time.Unix(startTime, 0)
	end := time.Unix(endTime, 0)

	return s.dbClient.QueryByWellAndTimeRange(wellID, start, end)
}

// GetCurrentMonthData 获取当月数据
func (s *WitsService) GetCurrentMonthData(limit int) ([]*WitsData, error) {
	currentMonth := time.Now().Format("200601")
	return s.dbClient.QueryByPartition(currentMonth, limit)
}

// GetPartitionInfo 获取分区信息
func (s *WitsService) GetPartitionInfo() ([]map[string]interface{}, error) {
	partitions, err := s.dbClient.GetPartitions()
	if err != nil {
		return nil, err
	}

	var partitionInfo []map[string]interface{}
	for _, partition := range partitions {
		stats, err := s.dbClient.GetPartitionStats(partition)
		if err != nil {
			log.Printf("Failed to get stats for partition %s: %v", partition, err)
			continue
		}

		info := map[string]interface{}{
			"partition":    partition,
			"record_count": stats["record_count"],
			"min_time":     stats["min_time"],
			"max_time":     stats["max_time"],
			"wells":        stats["wells"],
		}
		partitionInfo = append(partitionInfo, info)
	}

	return partitionInfo, nil
}
